package collector

import (
	"encoding/json"
	"github.com/gomodule/redigo/redis"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/log"
	"strconv"
)

type rancherHostCollector struct {
	Host *prometheus.Desc
}

func init() {
	registerCollector("host", defaultEnabled, rancherHostExporter)
}

func rancherHostExporter() (Collector, error) {
	return &rancherHostCollector{
		Host: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, "host", "state"),
			"rancher host state",
			[]string{
				"host_id",
				"rancher_env",
				"host_name",
				"uuid",
			},
			prometheus.Labels{
				"state_code_active":   strconv.FormatFloat(Active, 'f', -1, 64),
				"state_code_inactive": strconv.FormatFloat(Inactive, 'f', -1, 64),
			},
		),
	}, nil
}

func (rc rancherHostCollector) Update(ch chan<- prometheus.Metric) error {

	hosts, err := rc.GetHosts()

	if err != nil {
		return err
	} else {
		for _, host := range hosts {
			state := 0.0
			switch host.State {
			case "active":
				state = Active
			case "inactive":
				state = Inactive
			}
			ch <- prometheus.MustNewConstMetric(rc.Host, prometheus.GaugeValue, state,
				host.Id,
				host.RancherEnv,
				host.HostName,
					host.Uuid,
			)
		}
	}
	return nil
}

func (rc rancherHostCollector) GetHosts() (hosts []*Host, err error) {
	c := RedisPool.Get()
	if c.Err() != nil {
		log.Error(c.Err())
		return nil, err
	}
	defer c.Close()

	keys, err := redis.Strings(c.Do("KEYS", "host_*"))

	for _, key := range keys {
		ct, err := redis.Bytes(c.Do("GET", key))

		if err != nil {
			log.Error(err)
		} else {
			host := new(Host)
			json.Unmarshal(ct, &host)
			hosts = append(hosts, host)
		}
	}
	return hosts, err
}
